package com.bianguo.android.bprinter.utils;

import android.graphics.Bitmap;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class Print {

    private OutputStreamWriter writer;

    private Print(Builder builder) {
        this.writer = builder.writer;
    }


    public static class Builder {

        public OutputStreamWriter writer;
        public OutputStream os;

        public Builder setWriter(OutputStream os) throws UnsupportedEncodingException {
            this.os = os;
            this.writer = new OutputStreamWriter(os, "gbk");
            return this;
        }

        //初始化
        public Builder init() throws IOException {
            writer.write(0x1B);
            writer.write(0x40);
            writer.flush();
            return this;
        }

        /**
         * 设置文本对齐
         *
         * @param align 打印位置  0：居左(默认) 1：居中 2：居右
         * @return
         */
        public Builder setAlignPosition(int align) throws IOException {
            writer.write(0x1B);
            writer.write(0x61);
            writer.write(align);
            writer.flush();
            return this;
        }

        /**
         * 换行
         *
         * @throws IOException
         */
        public Builder nextLine() throws IOException {
            writer.write("\n");
            writer.flush();
            return this;
        }

        /**
         * 缩进
         *
         * @param length 缩进长度
         * @throws IOException
         */
        public Builder printTab(int length) throws IOException {
            for (int i = 0; i < length; i++) {
                writer.write("\t");
            }
            writer.flush();
            return this;
        }

        /**
         * 打印文字
         * @param txt
         * @throws IOException
         */
        public Builder printTxt(String txt) throws IOException {
            writer.write(txt);
            writer.flush();
            byte[] b = {0x1B, 0x64};
            os.write(b);
            os.write(5);
            return this;
        }

        /**
         * 打印图片
         * @param bitmap
         */
        public Builder printImg(Bitmap bitmap) throws IOException {
            byte[] readBitMapBytes = BitmapUtil.getReadBitMapBytes(BitmapUtil.convertToBlackWhite(bitmap));
            writer.write(new String(readBitMapBytes, "gbk"));
            writer.flush();
            return this;
        }

        public Print build() {
            return new Print(this);
        }
    }
}
